package com.milling.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.milling.business.service.IWmsNeedleSorttingService;
import com.milling.business.service.IWmsSortingInstockHistoryService;
import com.milling.common.core.redis.RedisCache;
import com.milling.common.utils.StringUtils;
import com.milling.common.utils.http.HttpUtils;
import com.milling.common.utils.modbus.ModbusServiceFactory;
import com.milling.common.utils.modbus.ModbusTcpService;
import com.milling.framework.websocket.AlertConfirmWebSocketHandler;
import com.milling.framework.websocket.WebSocketUsers;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 定时任务调度 - 分拣信息
 *
 * @author X
 */
@Configuration
@ConditionalOnProperty(
        name = "mac.type",
        havingValue = "2",
        matchIfMissing = false // 当配置缺失时不加载
)
@Component("sortingTask")
public class ViewSortingData
{
    private static final Logger logger = LoggerFactory.getLogger(ViewSortingData.class);

    // 从参数中读取IP、端口、slaveId和连接池大小
    @Value("${modbus.sorting.host:192.168.237.178}")
    private String host; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.port:502}")
    private int port; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.poolSize:5}")
    private int poolSize; // 从配置文件或命令行参数中读取

    @Value("${modbus.sorting.slaveId:1}")
    private int slaveId;

    @Autowired
    private RedisCache redisCache;

    // 获取Modbus服务实例
    private ModbusTcpService modbusTcpService;

    @PostConstruct
    public void init() {
        // 初始化 Modbus 服务
        modbusTcpService = ModbusServiceFactory.getModbusService(host, port, poolSize);
        logger.info("ViewSortingData Modbus服务初始化完成 - {}:{}", host, port);
    }

    public void ryMultipleParams(String s, Boolean b, Long l, Double d, Integer i)
    {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void ryParams(String params)
    {
        System.out.println("执行有参方法：" + params);
    }

    public void ryNoParams()
    {
        System.out.println("执行无参方法");
    }

    public void handlerTask()
    {
        // 模拟获取 PLC 寄存器数据，实际应用中应替换为真实的 PLC 数据获取逻辑
        boolean[] plcData = new boolean[600];
        for (int i = 0; i < 600; i++) {
            plcData[i] = false;
        }

        int block = 2;
        Random random = new Random();
        for (int m = (50 * block); m < (50*(block+1)); m++) {
//        for (int m = 0; m < plcData.length; m++) {
            plcData[m] = random.nextBoolean(); // 随机生成 0 或 1 作为示例
        }
/*
        for (int m = 0; m < 100; m++) {
//        for (int m = 0; m < plcData.length; m++) {
            plcData[m] = random.nextBoolean(); // 随机生成 0 或 1 作为示例
        }
        for (int j = 100; j < 600; j++) {
            plcData[i] = true;
        }
*/
//        return new PlcDataMessage(plcData);
// 将 boolean 数组转换为 JSON 字符串
// 使用 fastjson2 将 boolean 数组转换为 JSON 字符串
        String jsonPlcData = JSON.toJSONString(plcData);

        logger.info("sortingData 分拣数据: " + jsonPlcData);

// 构造一个统一的消息格式
        Map<String, Object> message = new HashMap<>();
        message.put("type", "data"); // 数据类型
        message.put("content", jsonPlcData);

        /// //////////  操作按钮状态start  ////////////
        //读取PLC操作功能地址及值
        //读取PLC操作功能地址及值
        int startAddress = 8192+1;
        int numberOfCoils = 4;

        try {
            boolean[] result = modbusTcpService.readCoilsMitsubishi(slaveId, startAddress, numberOfCoils);
            JSONObject jsonObject = new JSONObject();
            //1、启动
            //3、初始化
            //4、故障解除

            //2、暂停/继续        operate == 1 ? true : false
            jsonObject.put("start", result[0]);
            jsonObject.put("suspend", result[1]);
            jsonObject.put("initSort", result[2]);
            jsonObject.put("clearFault", result[3]);

            //1504、开关蜂鸣器    operate == 1 ? true : false
            result = modbusTcpService.readCoilsMitsubishi(slaveId, 8192+1504,1);
            jsonObject.put("buzzer", result[0]);

            message.put("operData", jsonObject);
        } catch (ModbusTransportException e) {
            logger.error("读取PLC操作功能地址异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        /// //////////  操作按钮状态end  ////////////

// 发送数据给前端
        WebSocketUsers.sendMessageToUsersByText(JSON.toJSONString(message));

    }

}
